<?php

// config

$loop = 20;

$reloadAfter = 5;

$precission = 2;

// collected data

$data = isset($_GET['data']) ? explode(',', $_GET['data']) : array();
if (sizeof($data) < $loop) {
	$data[] = testLoop($precission);
}
// lib

function testLoop($precission) {
	$start = micro_time();
	bigArray(400);
	return round((micro_time() - $start) * 1000, $precission);
} // testLoop

function bigArray($loop = 10) {
	for ($l = 0; $l < $loop; $l++) {
        $big = array();
        for ($i = 0; $i < 1000; $i++) {
            $big[] = 'lorem ipsum';
        }
        unset($big);
    }
} // bigArray

function calcStats($data) {
	$stat['mean'] = round(mean($data), 2);
	$stat['dev']  = round(standardDeviation($data), 2);
	return $stat;
} // calcStats

function mean($data) {
    $sum = 0;
    foreach ($data as $val) {
        $sum += $val;
    }
    return $sum/sizeof($data);
} // mean

function meanSquare($data) {
    $sum = 0;
    foreach ($data as $val) {
        $sum += $val*$val;
    }
    return $sum/sizeof($data);
} // mean

function standardDeviation($data) {
    $n = count($data);
	$mean = mean($data);
	return sqrt( ($n / ($n-1)) * (meanSquare($data) - $mean*$mean) );
} // standardDeviation


function micro_time($intPrec = 6){
    list($usec, $sec) = explode(' ', microtime());
    return round(floatval($usec) + floatval($sec), $intPrec);
} // micro_time

$out  = '<html>';
$out .= '<head>';
if (sizeof($data) < $loop) {
    $out .= '<meta http-equiv="refresh" content="'.$reloadAfter.';url=index.php?data='.implode(',', $data).'">';
} elseif (sizeof($data) == $loop && empty($_GET['done'])) {
    $out .= '<meta http-equiv="refresh" content="1;url=index.php?done=1&data='.implode(',', $data).'">';
}
$out .= '</head>';
$out .= '<body style="font-family: Tahoma; font-size: 11px">';
$out .= '<h1>Server Test Drive</h1>';
foreach ($data as $value) {
	$out .= $value.'<br>';
}
if (sizeof($data) < $loop) {
	$out .= '...';
} else {
	$stat = calcStats($data);
	$out .= '<br>DONE';
	$out .= '<br>';
	$out .= '<br>mean = '.$stat['mean'].' &#177; '.$stat['dev'].' [ms]';
    $out .= '<br>';
    $out .= '<br>';
    $out .= '<a href="index.php">AGAIN</a>';
}
$out .= '<br>';
$out .= '<br>';
$out .= '<br>';
$out .= '<small><a href="http://code.google.com/p/server-test-drive" target="_blank">Server Test Drive</a> ver. 0.1</small>';
$out .= '</body>';
$out .= '</html>';

echo $out;
